#include "voicecommands.h"

#include <QAudioEncoderSettings>
#include <QDir>
#include <QProcess>
#include <QUrl>

VoiceCommands::VoiceCommands()
{
    QAudioEncoderSettings audioSettings;
    audioSettings.setCodec("audio/pcm");
    audioSettings.setBitRate(8000);
    audioSettings.setChannelCount(1);

    audioRecorder.setEncodingSettings(audioSettings);
    resourcePath = QDir(QDir::currentPath().append("/../Resources/voiceCommands/"));
    audioRecorder.setOutputLocation(QUrl::fromLocalFile(resourcePath.absoluteFilePath("recording.raw")));
    mRecording = false;
}

QString VoiceCommands::recognize() {
    if( !mRecording ) {
        recognizedLine = "";

        QProcess script(this);
        script.setWorkingDirectory(resourcePath.absolutePath());
        script.start("./recognize.bash");
        script.waitForFinished();

        // Open the result (JSON file)
        QFile file(resourcePath.absoluteFilePath("recognized.json"));
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            return "";

        QTextStream in(&file);
        while (!in.atEnd()) {
            QString line = in.readLine();
            QString utt = "[{\"utterance\":\"";
            int start = line.indexOf(utt) + utt.size();
            line = line.mid(start);
            start = line.indexOf("\"");
            recognizedLine = line.left(start);
        }

    }

    return recognizedLine;
}

void VoiceCommands::startRecording() {
    mRecording = true;
    audioRecorder.record();
}

void VoiceCommands::stopRecording() {
    audioRecorder.stop();
    mRecording = false;
}
